package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInAppVo;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    /**
     * 申请入住
     *
     * @param dto
     */
    /**
     * 申请入驻
     *
     * @param checkInApplyDto
     */
    @Autowired
    private IBedService bedService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 查询入住详情
     *
     * @param id
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInAppVo detail(Long id) {
        //查询入住信息、
        CheckIn checkIn = this.selectCheckInById(id);
        if (checkIn==null){
            throw new BaseException("入住id不存在");
        }
        //查旬老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderService.selectElderById(elderId);
        CheckInElderVo checkInElderVo=new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);

        //查询家属列表
        Gson gson = new Gson();
        Type listType = new TypeToken<List<ElderFamilyVo>>() {}.getType();
        List<ElderFamilyVo> elderFamilyVoList = gson.fromJson(checkIn.getRemark(), listType);


        //查询配置信息
        CheckInConfig checkInConfig = checkInConfigService.getOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo=new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //查询合同
        Contract contract = contractService.getOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        CheckInAppVo checkInAppVo=new CheckInAppVo(checkInElderVo,elderFamilyVoList,checkInConfigVo,contract);


        return checkInAppVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void applicationStay(CheckInApplyDto dto) {
        //老人的身份证号
        String cardNo = dto.getCheckInElderDto().getIdCardNo();
        //1. 判断老人是否已入住 select count(*) from check_in where id_card_no=? and status=0
        Long countCheckIn = this.lambdaQuery().eq(CheckIn::getIdCardNo, cardNo)
                .eq(CheckIn::getStatus, 0).count();
        if (countCheckIn > 0) {
            throw new RuntimeException("老人已入住过");
        }
        //2. 判断符合要求的床位是否已存在 select * from bed where id=? and bed_status=0
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.lambdaQuery().eq(Bed::getId, bedId)
                .eq(Bed::getBedStatus, 0).one();
        if (bed == null) {
            throw new RuntimeException("床位不符合要求");
        }

        //3. 更新床位状态为已入住  update bed set bed_status=1 where id=?
        Bed bedDB = new Bed();
        bedDB.setId(bedId);
        bedDB.setBedStatus(1);//已入住
        boolean bedResult = bedService.updateById(bedDB);
        //        boolean bedResult =  bedService.lambdaUpdate().eq(Bed::getId,bed)
        //                .set(Bed::getBedStatus,1)
        //                .update();
        if (!bedResult) {
            throw new RuntimeException("更新床位失败");
        }
        //4. 新增或更新老人
        //查询老人信息 select * from elder where id_card_no=?
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, cardNo).one();
        if (elder == null) {
            elder = new Elder();
        }
        //拷贝老人信息
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedId(bedId);//床位ID
        elder.setBedNumber(bed.getBedNumber());//床位编号
        elder.setStatus(4);//入住中
        boolean resultElder = elderService.save(elder);
        if (!resultElder) {
            throw new RuntimeException("新增老人信息失败");
        }
/*
             //5. 新增签约信息（合同信息）
              Contract contract = new Contract();
              //拷贝合同信息
              BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
               contract.setElderId(elder.getId());//老人ID
               contract.setElderName(elder.getName());//老人姓名
               contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());//合同编号
              contract.setStartDate(dto.getCheckInConfigDto().getStartDate());//合同开始时间
               contract.setEndDate(dto.getCheckInConfigDto().getEndDate());//合同结束时间
               int status = LocalDateTime.now().isBefore(contract.getStartDate()) ? 0 : LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;//合同状态
               contract.setStatus(status);
               boolean resultContract = contractService.save(contract);
              if(!resultContract){
                       throw new RuntimeException("新增合同信息失败");
                    }*/
        Contract contract = new Contract();
        //拷贝合同信息
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());//老人ID
        contract.setElderName(elder.getName());//老人姓名
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());//合同编号
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());//合同开始时间
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());//合同结束时间
        int status = LocalDateTime.now().isBefore(contract.getStartDate()) ? 0 : LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;//合同状态
        contract.setStatus(status);
        boolean resultContract = contractService.save(contract);
        if (!resultContract) {
            throw new RuntimeException("新增合同信息失败");
        }

        //6. 新增入住信息
        CheckIn checkIn = new CheckIn();
        //拷贝入住信息
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());//老人姓名
        checkIn.setElderId(elder.getId());//老人ID
        checkIn.setIdCardNo(cardNo);//老人身份证号
        checkIn.setBedNumber(bed.getBedNumber());//床位编号
        checkIn.setStatus(0);//已入住
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//家属信息的JSON字符串
        boolean resultCheckIn = this.save(checkIn);
        if (!resultCheckIn) {
            throw new RuntimeException("新增入住信息失败");
        }
        //7. 新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        //拷贝入住配置信息
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());//入住信息id
        boolean resultCheckInfoConfig = checkInConfigService.save(checkInConfig);
        if (!resultCheckInfoConfig) {
            throw new RuntimeException("新增入住配置信息失败");
        }
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }
}
